﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace Lost{
	/// <summary>
	/// 场景重要物品管理
	/// </summary>
	public class ItemsManager : MonoBehaviour {
		public static ItemsManager _instance;
		///场景中的所有ItemTag，ICH是树状结构
		ICH SceneItems = new ICH ();
		[SerializeField] ItemTag[] hidenItems;

		#if UNITY_EDITOR
		///用数组的形式记录场景中的所有ItemTag
		public ItemTag[] AllItemTags{
			get{ 
				if (allItemTags.Length != SceneItems.CountAll) {
					allItemTags = SceneItems.GetAllItemTags ();
				}
				return allItemTags;
			}
		}
		[SerializeField] ItemTag[] allItemTags;
		#endif

		void Awake(){
			_instance = this;
			ItemTag[] allTagInScene = GameObject.FindObjectsOfType<ItemTag> ();
			foreach (ItemTag it in allTagInScene) {
				Insert (it);
			}
			foreach (ItemTag it in hidenItems) {
				Insert (it);
			}
			hidenItems = null;
			#if UNITY_EDITOR
			allItemTags = SceneItems.GetAllItemTags ();
			#endif
		}

		///插入
		public void Insert(ItemTag item){
			SceneItems.Insert (item);
		}
		///添加
		public static void Add(ItemTag it){
			ItemsManager._instance.SceneItems.Insert (it);
		}
		///查找
		public static ItemTag FindItemTag(string itemName){
			return _instance.SceneItems.FindItemTag (itemName);
		}
		public static Transform FindTransform(string itemName){
			return _instance.SceneItems.FindItemTag (itemName).transform;
		}
		public static GameObject FindGameObject(string itemName){
			return _instance.SceneItems.FindItemTag (itemName).gameObject;
		}
		///销毁ItemTag，单不销毁物体
		public static void iDestroy(ItemTag it){
			if (it == null) {
				return;
			}
			_instance.SceneItems.RemoveItemTag (it);
			Destroy (it);
			//Destroy (it.gameObject);
		}
		///销毁场景物体
		public static void iDestroy(GameObject obj){
			ItemTag it = obj.GetComponent<ItemTag> ();
			if (it != null) {
				_instance.SceneItems.RemoveItemTag (it);
			}
			Destroy (obj);
		}
		///生成场景物体
		public static GameObject iInstantiate(GameObject prefab, Vector3 pos=default(Vector3), Quaternion rotation=default(Quaternion)){
			if (prefab == null) {
				Debug.LogError ("You can't instantiate a null prefab!");
				return null;
			}
			if (pos == default(Vector3)) {
				pos = prefab.transform.position;
			}
			if (rotation == default(Quaternion)) {
				rotation = prefab.transform.rotation;
			}
			GameObject obj = GameObject.Instantiate (prefab, pos, rotation) as GameObject;
			ItemTag[] its = obj.GetComponentsInChildren<ItemTag> ();
			foreach (ItemTag it in its) {
				ItemsManager.Add (it);
			}
			return obj;
		}
	}
}
